'use client';

import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Statistic, Table, Progress, Tag, Avatar, List } from 'antd';
import {
  UserOutlined,
  ShoppingCartOutlined,
  DollarCircleOutlined,
  RiseOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined
} from '@ant-design/icons';
import AdminLayout from '@/components/AdminLayout';
import Link from 'next/link';

const AdminDashboard: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [dashboardData, setDashboardData] = useState<any>({});

  useEffect(() => {
    fetchDashboardData();
  }, []);

  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      
      // 模拟获取仪表盘数据
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      setDashboardData({
        stats: {
          totalUsers: 1245,
          totalOrders: 896,
          totalRevenue: 1234567.89,
          totalProducts: 156,
          userGrowth: 12.5,
          orderGrowth: 8.3,
          revenueGrowth: 15.2,
          productGrowth: 3.1
        },
        recentOrders: [
          { 
            id: 1, 
            orderNumber: 'ORD20240101001', 
            customer: '张三', 
            amount: 1299.00, 
            status: 'PAID',
            time: '2024-01-01 10:30'
          },
          { 
            id: 2, 
            orderNumber: 'ORD20240101002', 
            customer: '李四', 
            amount: 2580.00, 
            status: 'SHIPPED',
            time: '2024-01-01 11:15'
          },
          { 
            id: 3, 
            orderNumber: 'ORD20240101003', 
            customer: '王五', 
            amount: 899.00, 
            status: 'PENDING',
            time: '2024-01-01 12:20'
          }
        ],
        topProducts: [
          { name: '北极甜虾', sales: 456, revenue: 45600 },
          { name: '阿拉斯加帝王蟹', sales: 234, revenue: 234000 },
          { name: '挪威三文鱼', sales: 345, revenue: 34500 },
          { name: '澳洲龙虾', sales: 123, revenue: 98400 },
          { name: '新西兰青口贝', sales: 567, revenue: 28350 }
        ]
      });
    } catch (error) {
      console.error('获取仪表盘数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      'PENDING': 'orange',
      'PAID': 'blue',
      'SHIPPED': 'green',
      'DELIVERED': 'green',
      'CANCELLED': 'red'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status: string) => {
    const texts: Record<string, string> = {
      'PENDING': '待支付',
      'PAID': '已支付',
      'SHIPPED': '已发货',
      'DELIVERED': '已送达',
      'CANCELLED': '已取消'
    };
    return texts[status] || status;
  };

  const orderColumns = [
    {
      title: '订单号',
      dataIndex: 'orderNumber',
      key: 'orderNumber',
    },
    {
      title: '客户',
      dataIndex: 'customer',
      key: 'customer',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: number) => `¥${amount.toFixed(2)}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      ),
    },
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
    },
  ];

  // 销售趋势数据（模拟）
  const salesTrendData = [
    { month: '1月', sales: 125000 },
    { month: '2月', sales: 132000 },
    { month: '3月', sales: 141000 },
    { month: '4月', sales: 158000 },
    { month: '5月', sales: 162000 },
    { month: '6月', sales: 178000 },
  ];

  const categoryData = [
    { type: '海鲜类', value: 45 },
    { type: '贝类', value: 25 },
    { type: '鱼类', value: 20 },
    { type: '其他', value: 10 },
  ];

  const salesTrendConfig = {
    data: salesTrendData,
    xField: 'month',
    yField: 'sales',
    smooth: true,
    color: '#1890ff',
    point: {
      size: 5,
      shape: 'diamond',
      style: {
        fill: 'white',
        stroke: '#1890ff',
        lineWidth: 2,
      },
    },
  };

  const categoryConfig = {
    data: categoryData,
    angleField: 'value',
    colorField: 'type',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name} {percentage}',
    },
    interactions: [{ type: 'element-active' }],
  };

  return (
    <AdminLayout 
      selectedKey="1" 
      breadcrumbItems={[{ title: '仪表盘' }]}
    >
      <div style={{ padding: '24px' }}>
        <h1 style={{ marginBottom: '24px', fontSize: '24px', fontWeight: 'bold' }}>
          仪表盘总览
        </h1>

        {/* 统计卡片 */}
        <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总用户数"
                value={dashboardData.stats?.totalUsers || 0}
                prefix={<UserOutlined />}
                suffix={
                  <span style={{ fontSize: '14px', color: '#52c41a' }}>
                    <ArrowUpOutlined /> {dashboardData.stats?.userGrowth || 0}%
                  </span>
                }
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总订单数"
                value={dashboardData.stats?.totalOrders || 0}
                prefix={<ShoppingCartOutlined />}
                suffix={
                  <span style={{ fontSize: '14px', color: '#52c41a' }}>
                    <ArrowUpOutlined /> {dashboardData.stats?.orderGrowth || 0}%
                  </span>
                }
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总收入"
                value={dashboardData.stats?.totalRevenue || 0}
                prefix={<DollarCircleOutlined />}
                precision={2}
                suffix={
                  <span style={{ fontSize: '14px', color: '#52c41a' }}>
                    <ArrowUpOutlined /> {dashboardData.stats?.revenueGrowth || 0}%
                  </span>
                }
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="总产品数"
                value={dashboardData.stats?.totalProducts || 0}
                prefix={<RiseOutlined />}
                suffix={
                  <span style={{ fontSize: '14px', color: '#52c41a' }}>
                    <ArrowUpOutlined /> {dashboardData.stats?.productGrowth || 0}%
                  </span>
                }
              />
            </Card>
          </Col>
        </Row>

        {/* 图表区域 */}
        <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
          <Col xs={24} lg={16}>
            <Card title="销售趋势" style={{ height: '400px' }}>
              <div style={{ 
                height: 300, 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center',
                background: '#f5f5f5',
                borderRadius: '8px',
                color: '#666'
              }}>
                销售趋势图表 (需要安装 @ant-design/plots)
              </div>
            </Card>
          </Col>
          <Col xs={24} lg={8}>
            <Card title="产品分类分布" style={{ height: '400px' }}>
              <div style={{ 
                height: 300, 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center',
                background: '#f5f5f5',
                borderRadius: '8px',
                color: '#666'
              }}>
                分类分布饼图 (需要安装 @ant-design/plots)
              </div>
            </Card>
          </Col>
        </Row>

        {/* 数据表格和列表 */}
        <Row gutter={[16, 16]}>
          <Col xs={24} lg={16}>
            <Card title="最近订单" extra={<Link href="/admin/orders">查看全部</Link>}>
              <Table
                dataSource={dashboardData.recentOrders || []}
                columns={orderColumns}
                pagination={false}
                size="small"
                loading={loading}
              />
            </Card>
          </Col>
          <Col xs={24} lg={8}>
            <Card title="热销产品" extra={<Link href="/admin/products">查看全部</Link>}>
              <List
                dataSource={dashboardData.topProducts || []}
                loading={loading}
                renderItem={(item: any, index: number) => (
                  <List.Item>
                    <List.Item.Meta
                      avatar={<Avatar style={{ backgroundColor: '#1890ff' }}>{index + 1}</Avatar>}
                      title={item.name}
                      description={`销量: ${item.sales} | 收入: ¥${item.revenue.toLocaleString()}`}
                    />
                  </List.Item>
                )}
              />
            </Card>
          </Col>
        </Row>
      </div>
    </AdminLayout>
  );
};

export default AdminDashboard;